#include "hal.h"

#define CAN_TRANSMIT				1
#define CAN_RECEIVE					!CAN_TRANSMIT
#define TX_BUFFER_SIZE				4
#define RX_BUFFER_SIZE				2

void CAN_IRQHandler();


CAN_MSG_Type AFTxMsg[TX_BUFFER_SIZE]; //Acceptance Filter mode
CAN_MSG_Type AFRxMsg[RX_BUFFER_SIZE]; //Acceptance Filter mode

uint32_t CANRxCount = 0, CANTxCount = 0;
uint32_t CANErrCount = 0;

/**********************************************************************************
 * Descricao:
 *
 * Parametro(s):
 *					-
 * Retorno:
 *					-
 **********************************************************************************/
void hal_can_init_ (void){
	PINSEL_CFG_Type PinCfg;

	/*configurçao da CAN1
	CAN1: select P0.0 como RD1. e P0.1 como TD1*/
	PinCfg.Funcnum = 1;
	PinCfg.OpenDrain = 0;
	PinCfg.Pinmode = 0;
	PinCfg.Pinnum = 0;
	PinCfg.Portnum = 0;
	PINSEL_ConfigPin(&PinCfg);
	PinCfg.Pinnum = 1;
	PINSEL_ConfigPin(&PinCfg);

	//Inicializa a CAN1 com Baudrate de 500kbps
	CAN_Init(LPC_CAN1, 500000);

	//Habilita a  Interrupcaoo
	CAN_IRQCmd(LPC_CAN1, CANINT_RIE, ENABLE);

	//Enable CAN Interrupt
	NVIC_EnableIRQ(CAN_IRQn);
	CAN_SetAFMode(LPC_CANAF, CAN_Normal);

}

void CAN_IRQHandler()
{
	static uint8_t IntStatus;

	IntStatus = CAN_IntGetStatus(LPC_CAN1);
	//check receive interrupt
	if((IntStatus>>0)&0x01)
	{
		CAN_ReceiveMsg(LPC_CAN1, &AFRxMsg[CANRxCount]);
		CANRxCount++;
	}
}
